// pages/chooseClient/chooseClient.js
import * as API from '../../../api/contactsApi';
import * as util from '../../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholder: '输入客户名称/客户编码',
    searchWords: '',
    id: '',
    name: '',
    pageNo: 1,
    pageSize: 10,
    hasRequest: false,
    networkError: false,
    dataSource: [],
    hasMore: true,
    total: 0,
    currentIndex: '', // 当前选中的index
    checkedAll: false,
    checkedNum: 0,
    customId: '',
    customName: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      currentIndex: options.currentIndex
    });
    this.loadData(true)
  },

  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
    // 重新加载
    this.clear();
    this.loadData(false);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
 * 生命周期函数--监听页面卸载
 */
  onUnload: function () {

  },

  /**
   * 加载数据
   */
  loadData: function (options) {
    var postbody = {
      pageNo: 1,
      pageSize: 10,
      searchKey: this.data.searchKey
    };
    API.getCustomContastsList(postbody).then(res => {
      let arr = res.customList || [];
      if (!option) {
        arr = this.data.dataSource.concat(res.customList || []);
      }
      let hasMore = arr.length < res.totalCount;
      this.setData({
        dataSource: arr,
        hasMore: hasMore,
        hasRequest: true,
        total: res.totalCount
      });
    }, err => {

    })
  },

  /**
   * 点击单选
   */
  toggleCheck: function (e) {
    if (e.currentTarget && e.currentTarget.dataset.list) {
      let data = this.data.dataSource.map(el => {
        if (el.id == e.currentTarget.dataset.list.id) {
          el.checked = !el.checked;
        }
        return el;
      })
      const num = data.filter(el => el.checked).length;
      this.setData({
        dataSource: data,
        checkedNum: num,
        checkedAll: this.data.dataSource.length == num ? true : false
      })
    }
  },

  /**
   * 切换全选
   */
  toggleAll: function () {
    let status = !this.data.checkedAll;
    let data = this.data.dataSource.map(el => {
      el.checked = status;
      return el;
    })
    this.setData({
      dataSource: data,
      checkedAll: status,
      checkedNum: status ? this.data.dataSource.length : 0
    });

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 增量加载
    if (this.data.hasMore) {
      this.setData({
        pageNo: ++this.data.pageNo
      });
      this.loadData(false);
    }
  },

  clear: function () {
    this.setData({
      dataSource: [],
      hasMore: true,
      pageNo: 1,
      pageSize: 10,
    })
  },

  clearSearch: function () {
    this.setData({
      searchWords: '',
      pageNo: 1,
      pageSize: 10,
      hasMore: true,
      dataSource: [],
    });
    this.loadData(true);
  },

  loadData: function () {
    if (!this.data.hasMore) return;
    var postbody = {
      pageNo: 1,
      pageSize: 10,
      searchWords: this.data.searchWords
    };
    API.getCustomContastsList(postbody).then(res => {
      let arr = this.data.dataSource.concat(res.customList || []);
      let hasMore = arr.length < res.totalCount;
      this.setData({
        dataSource: arr,
        hasMore: true,
        hasRequest: true,
      });
    }, err => {

    });
  },


  onHandleSearch(e) {
    this.clear()
    this.setData({
      searchWords: e.detail
    });
    this.loadData(true);
  },

  handleSearch: function (e) {
    if (!e.detail) {
      wx.showToast({
        title: '请输入搜索关键字',
      })
      return;
    }
    this.setData({
      searchWords: e.detail,
      pageNo: 1,
      pageSize: 10,
      hasMore: true,
    });
    this.loadData(true);
  },

  /**
  * 点击完成
  */
  ensure: function () {
    const that = this;
    if (this.data.checkedNum !== 0) {
      wx.getStorage({
        key: 'choosedClient',
        success: function (res) {
          const customCode = res.data.code;
          const customId = res.data.id;
          const customName = res.data.name;
          wx.getStorage({
            key: 'sharedData',
            success: function (data) {
              const orderIds = data.data.map(el => ({ orderid: el.id }));
              const telephoneIds = that.data.dataSource.filter(el => el.checked).map(el => ({ telephone: el.contactWay }));
              const postbody = {
                customCode: customCode,
                customId: customId,
                customName: customName,
                orderList: orderIds,
                telephoneList: telephoneIds
              };
              API.messageSend(postbody).then(res => {
                wx.showToast({
                  title: '推送成功',
                  icon: 'none'
                });
                wx.removeStorage({ key: 'choosedClient' })
                wx.removeStorage({ key: 'choosedOrder' })
                setTimeout(() => {
                  wx.navigateBack()
                }, 2000);
              }, err => {
                wx.showToast({
                  title: err,
                  icon: 'none'
                });
              });
            }
          })
        },
        fail: function () {
          wx.showToast({
            title: '发送错误',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack()
          }, 2000);
        }
      });

    } else {
      wx.showToast({
        title: '请选择客户',
        icon: 'none'
      });
      return;
    }
  },

  gotoAdd: function (e) {
    util.preventMoreClick(this, () => {
      const id = e.currentTarget.dataset.id;
      const name = e.currentTarget.dataset.name;
      wx.navigateTo({ url: '../contactsAdd/contactsAdd?customId=' + id + '&=customName' + name });
    })
  },

  back: function (e) {
    util.preventMoreClick(this, () => {
      const id = e.currentTarget.dataset.id;
      const name = e.currentTarget.dataset.name;
      wx.setStorageSync('contact_add_custom_id', id);
      wx.setStorageSync('contact_add_custom_name', name);
      wx.navigateBack({
        delta: 1
      });
    })
  }
})